<template>
  <div class="container">
    <!-- 面包屑导航 -->
    <div class="topNav">
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ name: 'base' }">仓库系统</el-breadcrumb-item>
        <el-breadcrumb-item>库存余额表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div class="together-content">
      <!-- 搜索区域 -->
    <div class="search-form">
      <el-form :inline="true" :model="searchForm" size="small">
        <el-form-item label="截止时间" style="width:180px">
          <el-date-picker
            v-model="searchForm.date"
            type="date"
            placeholder=""
            value-format="YYYY-MM-DD"
            clearable
            
          />
        </el-form-item>
        <el-form-item label="仓库" style="width: 180px">
          <el-input v-model="input" readonly placeholder="选择仓库" @click="warehouseVisible = true" style="width: 180px"/>
        </el-form-item>
        <el-form-item label="商品名称">
          <el-select
            v-model="searchForm.productName"
            placeholder="请选择商品"
            clearable
            filterable
            style="width: 180px"
          >
            <el-option
              v-for="name in uniqueProductNames"
              :key="name"
              :label="name"
              :value="name"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="商品类别">
          <el-select
            v-model="searchForm.category"
            placeholder="请选择类别"
            clearable
            style="width: 180px"
          >
            <el-option
              v-for="cat in uniqueCategories"
              :key="cat"
              :label="cat"
              :value="cat"
            />
          </el-select>
        </el-form-item><br/>

        <el-form-item label="供应商">
          <el-select
            v-model="searchForm.supplier"
            placeholder="请选择供应商"
            clearable
            filterable
            style="width: 180px"
          >
            <el-option
              v-for="sup in uniqueSuppliers"
              :key="sup"
              :label="sup"
              :value="sup"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 分割线 -->
      <el-divider style="margin: 10px 0" />
    </div>

     <!-- 仓库搜索列表弹出对话框 -->
    <el-dialog
      v-model="warehouseVisible"
      title="仓库搜索列表"
      width="40%"
      style="height: auto;"
      draggable
      :show-close="true">
      <!-- 调用仓库的搜索组件 -->
      <WareHouse ref="warehouseRef" :info="{selection: true, no: false, name: true, code: true, status: false, op: false, outButton: true}"/>
      <br/><br/>
    </el-dialog>

    <!-- 导出和打印按钮 -->
    <div class="table-header-buttons">
      <el-button type="primary" size="small" @click="handleExport">导出</el-button>
      <el-button size="small" @click="handlePrint">打印</el-button>
    </div><br/>


    <!-- 表格容器 -->
    <el-table
      :data="displayData"
      border
      stripe
      :header-cell-style="{ background: '#f5f7fa', fontWeight: 'bold', }"
      style="width: 100%"
      :max-height="500"
      v-loading="loading"
      show-summary
      sum-text="总计"
    >
      <!-- 固定列 -->
      <el-table-column prop="productCode" label="商品编号" width="120"  align="center"/>
      <el-table-column prop="productName" label="商品名称" width="150" fixed align="center"/>
      <el-table-column prop="category" label="商品类别" width="100" align="center"/>
      <el-table-column prop="specification" label="规格型号" width="120" align="center"/>

      <el-table-column prop="location" label="库位" width="180" align="center">
        <template #default="{ row }">
          {{ row.location.join(',') }}
        </template>
      </el-table-column>

      <el-table-column prop="supplier" label="供应商" width="140" align="center"/>
      <el-table-column prop="baseUnit" label="基本单位" width="90" align="center"/>
      <el-table-column prop="assistUnit" label="副单位" width="110" align="center" />

      <!-- 合并的“所有库存”列 -->
      <el-table-column label="所有库存" align="center" >
        <el-table-column label="基本数量" prop="totalStock" width="100" align="center" />
        <el-table-column label="单位成本(元)" prop="unitCost" width="110" align="center" >
          <template #default="{ row }">
            {{ Number(row.unitCost).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="成本(元)" width="110" align="center">
          <template #default="{ row }">
            {{ (row.totalStock * row.unitCost).toFixed(2) }}
          </template>
        </el-table-column>
      </el-table-column>

      <!-- 动态生成各仓库库存列 -->
      <el-table-column 
        v-for="wh in warehouses"
        :key="wh.code"
        :label="wh.name"
        align="center"
      >
        <el-table-column
          :label="`基本数量`"
          width="110"
          align="center"
          :prop="`warehouseStock.${wh.code}`"
        >
          <template #default="{ row }">
            {{ row.warehouseStock[wh.code] || 0 }}
          </template>
        </el-table-column>
      </el-table-column>
    </el-table><br/>

    <!-- 分页 -->
      <div class="page-div">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="10"
          layout="total, ->, prev, pager, next, jumper"
          background
        />
      </div>
    </div>
    
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch} from 'vue'
import { ArrowRight } from '@element-plus/icons-vue'
import WareHouse from '@/views/basic/WareHouse.vue'

// 打印功能
const handlePrint = () => {
  window.print()
}

//仓库搜索选中结果
let warehouseVisible = ref(false)
let input = ref('')
let warehouseRef = ref();
watch(warehouseVisible, (newVisible) => {
  if(!newVisible) {
    if(warehouseRef.value) { //这里需要加上if判断，子组件中没有选择数据时为undefined，可能用于点击仓库，但是没选择，所以导致undefined报错
      input.value = warehouseRef.value.selectedArray.map(item => item.name).join(',')
      //获取到仓库编码，存数据库用，仓库name仅用作展示
      //用完之后清空，避免污染其他地方数据
      warehouseRef.value.clearSelected();
    }
  }
})


// 模拟数据（10条）
const rawData = ref([
  {
    productCode: 'SP0001',
    productName: '小麦啤酒',
    category: '饮品',
    specification: '500ml*24',
    location: ['A01-01-01', 'B02-03-04'],
    supplier: '青岛啤酒有限公司',
    baseUnit: '瓶',
    assistUnit: '1箱=24瓶',
    totalStock: 1000,
    unitCost: 3.5,
    warehouseStock: { WH001: 300, WH002: 200, WH003: 400, WH004: 100 }
  },
  {
    productCode: 'SP0002',
    productName: '巧克力',
    category: '食品',
    specification: '100g',
    location: ['C03-01-02'],
    supplier: '费列罗集团',
    baseUnit: '块',
    assistUnit: '1盒=12块',
    totalStock: 500,
    unitCost: 12.0,
    warehouseStock: { WH001: 100, WH002: 50, WH003: 300, WH004: 50 }
  },
  {
    productCode: 'SP0003',
    productName: '橄榄油',
    category: '调味品',
    specification: '500ml',
    location: ['D04-05-06', 'E01-02-03'],
    supplier: '意大利进口商',
    baseUnit: '瓶',
    assistUnit: '1箱=6瓶',
    totalStock: 240,
    unitCost: 68.0,
    warehouseStock: { WH001: 100, WH002: 80, WH003: 60, WH004: 0 }
  },
  {
    productCode: 'SP0004',
    productName: '矿泉水',
    category: '饮品',
    specification: '550ml*24',
    location: ['F06-07-08'],
    supplier: '农夫山泉股份有限公司',
    baseUnit: '瓶',
    assistUnit: '1箱=24瓶',
    totalStock: 2000,
    unitCost: 1.2,
    warehouseStock: { WH001: 800, WH002: 600, WH003: 400, WH004: 200 }
  },
  {
    productCode: 'SP0005',
    productName: '洗衣液',
    category: '日化',
    specification: '2kg',
    location: ['G01-01-01'],
    supplier: '蓝月亮科技有限公司',
    baseUnit: '瓶',
    assistUnit: '1箱=10瓶',
    totalStock: 350,
    unitCost: 25.0,
    warehouseStock: { WH001: 150, WH002: 100, WH003: 50, WH004: 50 }
  },
  {
    productCode: 'SP0006',
    productName: '抽纸',
    category: '日化',
    specification: '180抽*10包',
    location: ['H02-03-04'],
    supplier: '维达国际控股',
    baseUnit: '包',
    assistUnit: '1提=10包',
    totalStock: 1200,
    unitCost: 2.0,
    warehouseStock: { WH001: 400, WH002: 300, WH003: 300, WH004: 200 }
  },
  {
    productCode: 'SP0007',
    productName: '咖啡豆',
    category: '食品',
    specification: '1kg',
    location: ['I05-05-05'],
    supplier: '星巴克中国',
    baseUnit: '袋',
    assistUnit: '1箱=5袋',
    totalStock: 150,
    unitCost: 80.0,
    warehouseStock: { WH001: 50, WH002: 50, WH003: 30, WH004: 20 }
  },
  {
    productCode: 'SP0008',
    productName: '红酒',
    category: '饮品',
    specification: '750ml',
    location: ['J01-02-03', 'K04-05-06'],
    supplier: '法国波尔多酒庄',
    baseUnit: '瓶',
    assistUnit: '1箱=6瓶',
    totalStock: 180,
    unitCost: 120.0,
    warehouseStock: { WH001: 60, WH002: 60, WH003: 40, WH004: 20 }
  },
  {
    productCode: 'SP0009',
    productName: '坚果混合装',
    category: '食品',
    specification: '500g',
    location: ['L07-08-09'],
    supplier: '三只松鼠股份有限公司',
    baseUnit: '袋',
    assistUnit: '1箱=20袋',
    totalStock: 400,
    unitCost: 28.0,
    warehouseStock: { WH001: 100, WH002: 100, WH003: 100, WH004: 100 }
  },
  {
    productCode: 'SP0010',
    productName: '洗发水',
    category: '日化',
    specification: '750ml',
    location: ['M01-01-01'],
    supplier: '宝洁中国',
    baseUnit: '瓶',
    assistUnit: '1箱=12瓶',
    totalStock: 600,
    unitCost: 45.0,
    warehouseStock: { WH001: 200, WH002: 150, WH003: 150, WH004: 100 }
  }
])

// 搜索表单
const searchForm = reactive({
  date: '',
  productName: '',
  category: '',
  supplier: ''
})

// 计算唯一选项用于下拉框
const uniqueProductNames = computed(() => [...new Set(rawData.value.map(i => i.productName))])
const uniqueCategories = computed(() => [...new Set(rawData.value.map(i => i.category))])
const uniqueSuppliers = computed(() => [...new Set(rawData.value.map(i => i.supplier))])

// 过滤后的数据显示
const displayData = computed(() => {
  return rawData.value.filter(item => {
    const matchesDate = !searchForm.date || true // 可扩展为按历史快照查询
    const matchesName = !searchForm.productName || item.productName === searchForm.productName
    const matchesCat = !searchForm.category || item.category === searchForm.category
    const matchesSup = !searchForm.supplier || item.supplier === searchForm.supplier

    return matchesDate && matchesName && matchesCat && matchesSup
  })
})

// 加载状态
const loading = ref(false)

// 查询与重置
const handleQuery = () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
  }, 500)
}

const resetSearch = () => {
  searchForm.date = ''
  searchForm.productName = ''
  searchForm.category = ''
  searchForm.supplier = ''
}
</script>

<style scoped>

::v-deep(.el-table tbody tr:hover > td) {
  background-color: #edd4587d !important; /* 浅黄色背景 */
  border-bottom-color: #c78e39; /* 可选：边框也变色 */
}

::v-deep(.el-table .el-table__body td) {
  padding: 8px 0; /* 控制上下内边距，影响行高 */
  height: 55px;  /* 固定行高 */
}

::v-deep(.el-table .el-table__header th) {
  padding: 10px 0;
  height: 44px;
  background-color: #f5f7fa;
}

::v-deep(.el-table__footer) {
  background-color: #d6d847bc !important;
  font-weight: bold;
  font-size: 14px;
}
  
  /* 打印 */
  .table-header-buttons {
    margin-top: 10px;
    text-align: right;
  }
</style>